import static java.lang.Thread.sleep;

public class Test {
    /**
     * 线程安全
     *  synchronized()
     */
    public static void main2(String[] args) {
        /**
         * 锁的四个必要条件
         *      1.互斥性->一个线程拿到锁,其它线程就需要阻塞等待
         *      2.不可抢占->一个线程拿到锁,除非主动释放,否则其它锁无法获取
         *      3.请求和保持->一个线程拿到一把锁的前提下,又去获取其它锁
         *      4.循环等待->线程A等待线程B,线程B等待线程A
         */
    }
    public static void main(String[] args) throws InterruptedException {
        /**
         * 死锁
         *      1.一个线程多把锁
         *      2.两个线程 两把锁
         *      3.N个线程 M把锁
         */
        Object locker = new Object();
        Object locker2 = new Object();

        Thread t1 = new Thread(()->{
           synchronized(locker) {
               try {
                       sleep(1000);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
               synchronized (locker2) {
                   System.out.println("t1获取两把锁");
               }
           }
        });

        Thread t2 = new Thread(()->{
           synchronized(locker2) {
               try {
                       sleep(1000);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
               synchronized (locker) {
                   System.out.println("t2获取两把锁");
               }
           }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();
    }
}
